# static_rnn()是使用链式cells实现一个按时间轴展开的RNN
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)

n_inputs = 3 #每个样本3个特征
n_neurons = 5 #隐藏状态，神经元个数

X0 = tf.placeholder(tf.float32, [None, n_inputs])  #每个输入的长度=3
X1 = tf.placeholder(tf.float32, [None, n_inputs])

#最基本的RNN神经单元
basic_cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neurons)  #n_neurons隐藏层单元个数

# 输入维度是2*4*3, 输出output_seqs维度4*5(包括Y0+Y1，所有单元的输出), states=Y1(最后一个单元的输出)
output_seqs, states = tf.contrib.rnn.static_rnn(basic_cell, [X0, X1], dtype=tf.float32)
Y0, Y1 = output_seqs

X0_batch = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 0, 1]])  #(4,3)
X1_batch = np.array([[9, 8, 7], [0, 0, 0], [6, 5, 4], [3, 2, 1]])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    Y0_val, Y1_val, out, states_ = sess.run([Y0, Y1, output_seqs,states], feed_dict={X0: X0_batch, X1: X1_batch})

print("Y0_val:\n",Y0_val)
print("Y1_val:\n",Y1_val)
print("out_put:\n",out)
print('states:\n', states_)

'''
Y0_val:
 [[-0.20199537 -0.44326904 -0.5206003  -0.53441274  0.39459777]
 [ 0.9106469  -0.71642625 -0.13083915 -0.9587885  -0.605005  ]
 [ 0.99710023 -0.8678334   0.3040497  -0.9970866  -0.94876295]
 [ 0.9984848   0.99429077  0.9999413  -0.99912316 -0.9991254 ]]
Y1_val:
 [[ 0.9999792  -0.75102216  0.9533074  -0.997718   -0.99824184]
 [-0.3146074  -0.07588408  0.2768853  -0.4950269   0.6803987 ]
 [ 0.99759805 -0.2723159   0.9570501  -0.9929273  -0.9243889 ]
 [ 0.6056263  -0.0243378   0.79376715 -0.6114615  -0.760844  ]]
states:
 [[ 0.9999792  -0.75102216  0.9533074  -0.997718   -0.99824184]
 [-0.3146074  -0.07588408  0.2768853  -0.4950269   0.6803987 ]
 [ 0.99759805 -0.2723159   0.9570501  -0.9929273  -0.9243889 ]
 [ 0.6056263  -0.0243378   0.79376715 -0.6114615  -0.760844  ]]

'''
'''
    tf.nn.static_rnn
    传参：
        basic_cell：基本RNN神经单元
        [X0, X1]输入两组参数
        dtype=输入的类型
    返回值：
        outputs的长度为T的列表（每个输入一个），或这些元素的嵌套元组
        最终状态
'''